package cn.leaf.service.impl;

import cn.leaf.constants.Constant;
import cn.leaf.req.MsgReq;
import cn.leaf.service.MessageService;
import cn.leaf.util.JacksonUtil;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 *
 * description: 消息接口实现类
 *
 * @author Cyril
 * @version v1.0.0
 * @since 2021-05-20 21:39:27
 *
 */
@Service
public class MessageServiceImpl implements MessageService {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Override
    public void sendMessage(MsgReq req) {
        String msg = JacksonUtil.bean2Json(req);
        assert msg != null;

        // 1. TODO 为了保证消息不丢失数据库冗余消息，设置状态字段为0，当消息投递成功时修改为1 Column：status(0: 还未投递成功 1：投递成功)

        // 2. 发送消息
        rabbitTemplate.convertAndSend(Constant.MESSAGE_DIRECT_EXCHANGE, Constant.MESSAGE_DIRECT_ROUTING_KEY, msg, new CorrelationData(req.getId()));
    }
}